//
//  LLoadingView.swift
//  AnimationDemo
//
//  Created by 李明明 on 16/1/28.
//  Copyright © 2016年 李明明. All rights reserved.
//

import UIKit

class LLoadingView: UIView {
    
    let kBeganStroke = "strokeEnd"
    let kEndStroke = "strokeStart"
    let kAnimationKey = "line"
    let oneAction = Selector("one")
    let twoAction = Selector("two")
    var shapeLayer: CAShapeLayer!
    var path: UIBezierPath! = UIBezierPath()
    var currentAngle: CGFloat! = 0
    var currentA: CGFloat! = 0
    var bgView: UIView! = UIView()
    var cycleTime: CGFloat! {   // 转一个圈的周期
        willSet {
            self.makePath()
            NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(newValue * 2), target: self, selector: oneAction, userInfo: nil, repeats: true)
        }didSet {
            
        }
        
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
    }
    init(frame: CGRect, view: UIView) {
        super.init(frame: frame)
        bgView.frame = frame
        bgView.center = view.center
        view.addSubview(bgView)
        bgView.addSubview(self)
        self.frame = frame
        center = CGPointMake(bgView.bounds.width / 2, bgView.bounds.height / 2)
    }
    func makePath() {
        self.shapeLayer = CAShapeLayer()
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.layer.addSublayer(self.shapeLayer)
            self.makeLayer(self.kBeganStroke)
        }
    }
    // 第一段动画
    func one() {
        addAnimation(kBeganStroke)
        performSelector(twoAction, withObject: nil, afterDelay: NSTimeInterval(cycleTime))
    }
    // 第二段动画
    func two() {
        addAnimation(kEndStroke).removedOnCompletion = true
    }
    func addAnimation(type: String)->CABasicAnimation {
        let animation = CABasicAnimation(keyPath: type)
        animation.fromValue = 0
        animation.toValue = 1
        animation.duration = CFTimeInterval(cycleTime)
        shapeLayer.addAnimation(animation, forKey: kAnimationKey)
        UIView.animateWithDuration(NSTimeInterval(cycleTime)) { () -> Void in
            self.currentA = CGFloat(M_PI_2) + self.currentA
            self.transform = CGAffineTransformRotate(CGAffineTransformIdentity, self.currentA)
        }
        return animation
    }
    func makeLayer(keyPath: String)-> CAShapeLayer {
        let r = bounds.height / 2 - 5
        let center = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
        let subpath = UIBezierPath()
        subpath.addArcWithCenter(center, radius: r, startAngle: currentAngle, endAngle: currentAngle + CGFloat(2 * M_PI), clockwise: true)
        one()
        path.appendPath(subpath)
        shapeLayer.path = path.CGPath
        shapeLayer.fillColor = UIColor.clearColor().CGColor
        shapeLayer.strokeColor = UIColor.greenColor().CGColor
        return shapeLayer
    }
    func stopLoading() {
        bgView.removeFromSuperview()
    }
}
